package com.ruoyi.system.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.NewsMapper;
import com.ruoyi.system.domain.News;
import com.ruoyi.system.service.IHatchetSystemConfigService;
import com.ruoyi.system.service.INewsService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.AliyunOssUtil;
import com.ruoyi.common.utils.Constans;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
/**
 * 新闻 服务层实现
 * 
 * @author ruoyi
 * @date 2019-06-13
 */
@Service
public class NewsServiceImpl implements INewsService 
{
	@Autowired
	private NewsMapper newsMapper;
	
	@Autowired
	private IHatchetSystemConfigService configService;
	/**
     * 查询新闻信息
     * 
     * @param id 新闻ID
     * @return 新闻信息
     */
    @Override
	public News selectNewsById(Integer id)
	{
	    return newsMapper.selectNewsById(id);
	}
	
	/**
     * 查询新闻列表
     * 
     * @param news 新闻信息
     * @return 新闻集合
     */
	@Override
	public List<News> selectNewsList(News news)
	{
	    return newsMapper.selectNewsList(news);
	}
	
    /**
     * 新增新闻
     * 
     * @param news 新闻信息
     * @return 结果
     */
	@Override
	public int insertNews(News news)
	{
	    return newsMapper.insertNews(news);
	}
	
	
	
	/**
     * 修改新闻
     * 
     * @param news 新闻信息
     * @return 结果
     */
	@Override
	public int updateNews(News news)
	{
	    return newsMapper.updateNews(news);
	}

	/**
     * 删除新闻对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteNewsByIds(String ids)
	{
		return newsMapper.deleteNewsByIds(Convert.toStrArray(ids));
	}
	
	 /**
     * 批量添加新闻
     * 
     * @param news 新闻信息
     * @return 结果
	 * @throws IOException 
     */
	@Override
	public int insertBatchNews(List<News> newsList) throws Exception{
	    return newsMapper.insertNews(newsList);
	}
	
	public List<News> flushNews(/*HttpServletRequest request*/) throws Exception{
		List<News> newsList = new ArrayList<>();
		String type = "top,shehui,guonei,guoji,yule,tiyu,junshi,keji,caijing,shishang";
		String[] split = type.split(",");
		String pageHead = "<html>";
		String pagefoot = "</body></html>";
		for (int i =0;i<split.length;i++) {
			String sendGet = HttpUtils.sendPost("http://v.juhe.cn/toutiao/index","type=" + split[i] +"&key=ed7c581f903c7360459a81d815f136ea");
			JSONObject json = JSONObject.parseObject(sendGet);
			Object object = json.get("result");
			json = JSONObject.parseObject(object.toString());
			Object x = json.get("data");
			JSONArray array = (JSONArray) x;
			Iterator<Object> iterator = array.iterator();
			while (iterator.hasNext()) {
				Object next = iterator.next();
				json = JSONObject.parseObject(next.toString());
				String author_name = json.getString("author_name");
				if ("央视网".equals(author_name.trim()) ||"中国新闻网".equals(author_name.trim()) ||
					"中国经济网".equals(author_name.trim()) ||"北京商报网".equals(author_name.trim())||
					"北青网".equals(author_name.trim()) ||"光明网".equals(author_name.trim()) ||	
					"新京报".equals(author_name.trim()) ||"环球网".equals(author_name.trim()) ||	
					"中国青年网".equals(author_name.trim())|| "人民网".equals(author_name.trim()) ||	
					"新华网".equals(author_name.trim()) ||"中国网".equals(author_name.trim()) ||	
					"新华社".equals(author_name.trim()) ||"中华人民共和国财政部".equals(author_name.trim()) ||	
					"中国军网".equals(author_name.trim()) ||"解放网".equals(author_name.trim()) ||	(author_name.trim().indexOf("中国")!=-1)||
					(author_name.trim().indexOf("光明")!=-1) ||(author_name.trim().indexOf("人民")!=-1) ||(author_name.trim().indexOf("中华")!=-1)||
					(author_name.trim().indexOf("中央")!=-1) 
						) {
					continue;
				}
				String date = json.getString("date");
				String thumbnail_pic_s = json.getString("thumbnail_pic_s");
				String title = json.getString("title");
				String url = json.getString("url");
				String uniquekey = json.getString("uniquekey");
				/*System.out.println(author_name);
				System.out.println(date);
				System.out.println(thumbnail_pic_s);
				System.out.println(title);
				System.out.println(url);
				System.out.println(uniquekey);*/
				Document doc = null;
				News newsParam = new News();
				newsParam.setUniquekey(uniquekey);
				List<News> selectNewsList = selectNewsList(newsParam);
				if (StringUtils.isNotEmpty(selectNewsList)) {
					continue;
				}
				try {
					doc = Jsoup.connect(url).get();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String J_article = doc.getElementById("J_article").html();
			/*	//获得项目地址
				String serverRealPath = request.getSession().getServletContext().getRealPath("/");
			   //转成tomcat的webapp路径
				String tomPath = serverRealPath.substring(0, serverRealPath.length()-1);//去掉最后一个斜杠
				//C:\Users\zhouqi\Documents\工作资源\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\ruoyi-admin
				tomPath = tomPath.replaceAll("\\\\", "/");
				//获得tomcatwebapp下面最后的/的索引
				int lastIndexOf = tomPath.lastIndexOf("/");
				//得到tomcat地址
				tomPath = tomPath.substring(0,lastIndexOf);*/
				//拼接页面存放地址
				String tomcatPath = configService.selectValueByCode("tomcat_webapps_path");
				
				String fileHead = tomcatPath+"/html/news/";
				String fileFoot = ".html";
				File htmlDir = new File(fileHead);
				if (!htmlDir.exists()) {
					htmlDir.mkdirs();
				}
				String path = fileHead + uniquekey + fileFoot;
				//String path = "/Users/knight.yang/Documents/dev/news/" + uniquekey + ".html";
//				java.io.File file = new java.io.File(path);
//				if (!file.exists())
//					file.createNewFile();
				News news = new News();
				news.setTitle(title);
				news.setType(split[i]);
				news.setAuthorName(author_name);
				news.setDate(date);
				news.setThumbnailPicS(thumbnail_pic_s);
				news.setUrl(url);
				news.setUniquekey(uniquekey);
				news.setCreateTime(DateUtils.parseDate(date));
				insertNews(news);
				//FileWriter fw = new FileWriter(path);
				BufferedWriter fw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (path,true),"UTF-8"));
				StringBuffer sb = new StringBuffer();
				sb.append("<div style='font-size:large;color:red;padding-top:10px;'>");
				sb.append("转载自：");
				sb.append(author_name);
				sb.append("&nbsp;&nbsp;<a color='blue' href='");
				sb.append(url);
				sb.append("'>阅读原新闻</ a><br/><br/>");
				sb.append("</div>");
				fw.write(pageHead + doc.head().toString() +sb.toString()+ J_article + pagefoot);
				fw.close();
				File file = new File(path);
				InputStream input = new FileInputStream(file);
				String uploadHtml = AliyunOssUtil.uploadHtml(uniquekey+".html", input);
				/*//删除本地文件
				file.delete();*/
			}
		}
		return newsList;
	}
	
	
}
